package com.ruoyi.project.infobaseproject.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelReader;
import com.ruoyi.beforehand.domain.InfoBeforehandEvaluate;
import com.ruoyi.beforehand.mapper.InfoBeforehandEvaluateMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.RedisUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.evaluate.infoprojectevaluate.domain.InfoProjectEvaluate;
import com.ruoyi.evaluate.infoprojectevaluate.mapper.InfoProjectEvaluateMapper;
import com.ruoyi.monitor.infoprojectmonitor.domain.InfoProjectMonitor;
import com.ruoyi.monitor.infoprojectmonitor.mapper.InfoProjectMonitorMapper;
import com.ruoyi.project.infoBaseProjectStatist.domain.InfoBaseProjectStatist;
import com.ruoyi.project.infoBaseProjectStatist.mapper.InfoBaseProjectStatistMapper;
import com.ruoyi.project.infobaseproject.domain.*;
import com.ruoyi.project.infobaseproject.mapper.InfoBaseProjectMapper;
import com.ruoyi.project.infobaseproject.mapper.InfoBaseProjectTargetStagingMapper;
import com.ruoyi.project.infobaseproject.mapper.InfoProjectTargetAdjustMapper;
import com.ruoyi.project.infobaseproject.service.IInfoBaseProjectService;
import com.ruoyi.project.infobaseproject.vo.HomePVO;
import com.ruoyi.project.infobaseproject.vo.ProjectReleaseVo;
import com.ruoyi.project.infobaseproject.vo.ProjectTargetVo;
import com.ruoyi.project.infobaseprojectindex.domain.InfoBaseProjectIndex;
import com.ruoyi.project.infobaseprojectindex.mapper.InfoBaseProjectIndexMapper;
import com.ruoyi.project.infoprojectbasetype.mapper.InfoProjectBaseTypeMapper;
import com.ruoyi.project.infoprojectcapitalannex.domain.InfoProjectCapitalAnnex;
import com.ruoyi.project.infoprojectcapitalannex.service.IInfoProjectCapitalAnnexService;
import com.ruoyi.project.infoprojecttarget.domain.InfoProjectTarget;
import com.ruoyi.project.infoprojecttarget.mapper.InfoProjectTargetMapper;
import com.ruoyi.project.infoprojecttarget.service.impl.InfoProjectTargetServiceImpl;
import com.ruoyi.project.infoprojecttarget.vo.AdjustTargetVo;
import com.ruoyi.project.infoprojecttarget.vo.StatistDeptVo;
import com.ruoyi.project.infoprojecttargetindex.domain.InfoProjectTargetIndex;
import com.ruoyi.project.infoprojecttargetindex.mapper.InfoProjectTargetIndexMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 项目库Service业务层处理
 *
 * @author ruoyi
 * @date 2022-01-24
 */
@Service
public class InfoBaseProjectServiceImpl implements IInfoBaseProjectService {
    @Resource
    private InfoBaseProjectMapper infoBaseProjectMapper;
    @Resource
    private InfoProjectTargetMapper infoProjectTargetMapper;
    @Resource
    private InfoBaseProjectIndexMapper infoBaseProjectIndexMapper;
    @Resource
    private InfoProjectTargetIndexMapper infoProjectTargetIndexMapper;
    @Resource
    private IInfoProjectCapitalAnnexService infoProjectCapitalAnnexService;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private InfoBaseProjectStatistMapper infoBaseProjectStatistMapper;
    @Resource
    private RedisUtil redisUtil;

    @Resource
    private InfoProjectBaseTypeMapper infoProjectBaseTypeMapper;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysUserService sysUserService;

    @Resource
    private InfoBeforehandEvaluateMapper infoBeforehandEvaluateMapper;

    @Resource
    private InfoProjectMonitorMapper infoProjectMonitorMapper;

    @Resource
    private InfoProjectEvaluateMapper infoProjectEvaluateMapper;

    @Resource
    private InfoProjectTargetAdjustMapper infoProjectTargetAdjustMapper;

    @Resource
    private InfoBaseProjectTargetStagingMapper infoBaseProjectTargetStagingMapper;

    @Resource
    private InfoProjectTargetServiceImpl infoProjectTargetService;

    /**
     * 查询项目库
     *
     * @param id 项目库主键
     * @return 项目库
     */
    @Override
    public InfoBaseProject selectInfoBaseProjectById(Long id) {
        InfoBaseProject infoBaseProject = infoBaseProjectMapper.selectInfoBaseProjectById(id);
        if (infoBaseProject.getProjectNode() != null) {
            String name = infoProjectBaseTypeMapper.selectInfoProjectBaseTypeById(Long.valueOf(infoBaseProject.getProjectNode())).getName();
            infoBaseProject.setProjectTypeName(name);
        }
        if (infoBaseProject.getDepartmentId() != null) {
            String deptName = sysDeptMapper.selectDeptById(infoBaseProject.getDepartmentId()).getDeptName();
            infoBaseProject.setDepartmentName(deptName);
        }
        SysDept sysDept = sysDeptMapper.selectDeptById(Long.valueOf(infoBaseProject.getWorkCompany()));
        infoBaseProject.setWorkCompanyName(sysDept.getDeptName());
        return infoBaseProject;
    }

    /**
     * 查询项目库列表
     * 循环查询子项目列表
     *
     * @param infoBaseProject 项目库
     * @return 项目库
     */
    @Override
    public List<InfoBaseProject> selectInfoBaseProjectList(InfoBaseProject infoBaseProject) {
        return infoBaseProjectMapper.selectInfoBaseProjectList(infoBaseProject);
    }

    /**
     * 新增项目库
     *
     * @param infoBaseProject 项目库
     * @return 结果
     */
    @Override
    public int insertInfoBaseProject(InfoBaseProject infoBaseProject) {

        Long deptId = SecurityUtils.getDeptId();
        infoBaseProject.setAncestors(deptId.toString());
        infoBaseProject.setCreateTime(DateUtils.getNowDate());
        return infoBaseProjectMapper.insertInfoBaseProject(infoBaseProject);
    }

    /**
     * 修改项目库
     *
     * @param infoBaseProject 项目库
     * @return 结果
     */
    @Override
    public int updateInfoBaseProject(InfoBaseProject infoBaseProject) {
        //InfoBaseProject infoBaseProject1 = infoBaseProjectMapper.selectInfoBaseProjectById(infoBaseProject.getId());
//        if (infoBaseProject1.getCreateBy() == null) {
//            Object loginUser = SecurityUtils.getLoginUser().getUser().getUserName();
//            infoBaseProject.setCreateBy(loginUser.toString());
//            infoBaseProject.setReleaseStatus(0);
//        }
//        infoBaseProject.setCreateByTime(DateUtils.getNowDate());
//        if (infoBaseProject.getOtherFund() != null || infoBaseProject.getCentralFund() != null || infoBaseProject.getProvincialFunds() != null) {
//            infoBaseProject.setIsXg(1);
//        }
        return infoBaseProjectMapper.updateInfoBaseProject(infoBaseProject);
    }

    /**
     * 批量删除项目库
     *
     * @param ids 需要删除的项目库主键
     * @return 结果
     */
    @Override
    public int deleteInfoBaseProjectByIds(Long[] ids) {
        infoBaseProjectMapper.deleteInfoBaseProjectByIds(ids);
        infoBaseProjectMapper.deleteInfoBaseProjectByIdss(ids);
        infoBaseProjectStatistMapper.deleteInfoBaseProjectStatistByIdss(ids);
        return infoBaseProjectStatistMapper.deleteInfoBaseProjectStatistByIds(ids);
    }

    /**
     * 删除项目库信息
     *
     * @param id 项目库主键
     * @return 结果
     */
    @Override
    public int deleteInfoBaseProjectById(Long id) {
        return infoBaseProjectMapper.deleteInfoBaseProjectById(id);
    }

    @Override
    public List<InfoBaseProject> selectInfoBaseChildProjectList(InfoBaseProject parentProject) {
        return infoBaseProjectMapper.selectInfoBaseProjectByParentId(parentProject);
    }

    @Override
    public List<InfoBaseProject> selectInfoBaseProjects(InfoBaseProject infoBaseProject) {
        return infoBaseProjectMapper.selectInfoBaseProjects(infoBaseProject);
    }

    @Override
    @Transactional
    public int projectRelease(ProjectReleaseVo projectReleaseVo) {
        //1.查验该项目是否存在
        InfoBaseProject infoBaseProject = infoBaseProjectMapper.selectInfoBaseProjectById(projectReleaseVo.getProjectId());
        if (null == infoBaseProject) {
            throw new ServiceException("项目不存在");
        }
        //2.将项目下达状态 由未下达改为已下达 0 未下达 1已下达
        infoBaseProject.setReleaseStatus(1);
        infoBaseProjectMapper.updateInfoBaseProject(infoBaseProject);
        //3.复制项目信息到目标填报的表中 info_project
        InfoProjectTarget infoProjectTarget = new InfoProjectTarget();
        //对象拷贝
        BeanUtils.copyProperties(infoBaseProject, infoProjectTarget);
        infoProjectTarget.setExamineStatus(0);
        infoProjectTarget.setBaseProjectId(infoBaseProject.getId());
        //存审计处的部门
        String userName = infoBaseProject.getCreateBy();
        //查他所属的部门
        SysUser sysUser = sysUserMapper.selectUserByUserName(userName);
        Long deptIds = sysUser.getDeptId();
        infoProjectTarget.setDeptId(deptIds);
        infoProjectTarget.setCreateTime(new Date());


        /**
         * 取消选择预算单位id（主管处室下达不选择预算单位了2022.3.28修改
         */
        //赋值 预算单位Id
//        infoProjectTarget.setReleaseDepartmentId(projectReleaseVo.getDeptId());
        //获取work_company
        String workCompany = infoBaseProject.getWorkCompany();
        //查他的id
        Long deptId = sysDeptMapper.selectDeptListss(workCompany);
        //塞到cenDepartmentId
        infoProjectTarget.setReleaseDepartmentId(deptId);
        infoProjectTarget.setCreateByTime(new Date());

        //下达备注
        infoProjectTarget.setReleaseRemarks(projectReleaseVo.getRemarks());
        //项目来源类型 0 目标填报中新增  1 项目库下达下来
        infoProjectTarget.setProjectAddType(1);
        int i = infoProjectTargetMapper.insertInfoProjectTarget(infoProjectTarget);
        //4.复制指标
        //4.1 查询基础库中的指标
        InfoBaseProjectIndex infoBaseProjectIndex = new InfoBaseProjectIndex();
        infoBaseProjectIndex.setProjectId(projectReleaseVo.getProjectId());
        List<InfoBaseProjectIndex> infoBaseProjectIndices = infoBaseProjectIndexMapper.selectInfoBaseProjectIndexList(infoBaseProjectIndex);
        for (InfoBaseProjectIndex baseProjectIndex : infoBaseProjectIndices) {
            InfoProjectTargetIndex infoProjectTargetIndex = new InfoProjectTargetIndex();
            BeanUtils.copyProperties(baseProjectIndex, infoProjectTargetIndex);
            infoProjectTargetIndex.setProjectId(infoProjectTarget.getId());
            infoProjectTargetIndexMapper.insertInfoProjectTargetIndex(infoProjectTargetIndex);
        }
        //5.复制 资金文件
        //5.1 先查询基础库中的资金文件附件
        InfoProjectCapitalAnnex infoProjectCapitalAnnexBase = new InfoProjectCapitalAnnex();
        infoProjectCapitalAnnexBase.setProjectType(0);
        infoProjectCapitalAnnexBase.setProjectId(infoBaseProject.getId());
        List<InfoProjectCapitalAnnex> infoProjectCapitalAnnexes = infoProjectCapitalAnnexService.selectInfoProjectCapitalAnnexList(infoProjectCapitalAnnexBase);
        if (!infoProjectCapitalAnnexes.isEmpty()) {
            for (InfoProjectCapitalAnnex infoProjectCapitalAnnex : infoProjectCapitalAnnexes) {
                infoProjectCapitalAnnex.setId(null);
                infoProjectCapitalAnnex.setProjectId(infoProjectTarget.getId());
                infoProjectCapitalAnnex.setProjectType(1);
                infoProjectCapitalAnnexService.insertInfoProjectCapitalAnnex(infoProjectCapitalAnnex);
            }
        }
        return i;
    }

    @Override
    public int insertInfoBaseProjects(ProjectVo projectVo) {
        //一级项目名称
        String yjxmmc = projectVo.getYjxmmc();
        //将一级项目名称存到数据库中
        InfoBaseProject infoBaseProject = new InfoBaseProject();
        infoBaseProject.setProjectName(yjxmmc);
        //存储创建人，创建时间，主管处室
        Object loginUser = SecurityUtils.getLoginUser().getUser().getUserName();
        infoBaseProject.setCreateBy(loginUser.toString());
        infoBaseProject.setCreateByTime(DateUtils.getNowDate());
        //主管处室id
        SysUser sysUser = sysUserMapper.selectUserByUserName(loginUser.toString());
        Long deptId = sysUser.getDeptId();
        infoBaseProject.setDepartmentId(deptId);
        SysDept sysDept = sysDeptMapper.selectDeptById(deptId);
        infoBaseProject.setDepartmentName(sysDept.getDeptName());
        infoBaseProjectMapper.insertInfoBaseProject(infoBaseProject);
        //遍历
        List<String> list = projectVo.getEjxmmcList();
        List<String> list1 = projectVo.getEjxmzjList();
        List<String> list2 = projectVo.getQy();
        //各自循环遍历
        for (int i = 0; i < list.size() - 2; i++) {
            //二级项目名称
            //判断若为null就不存
            if (list.get(i + 2) != null) {
                Object ejxmmc = list.get(i + 2);
                infoBaseProject.setProjectName(ejxmmc.toString());
            }
            for (int j = i; j <= i; j++) {
                //二级项目资金
                if (list1.get(j + 2) != null) {
                    Object ejxmjz = list1.get(j + 2);
                    BigDecimal ejxmjz1 = new BigDecimal(String.valueOf(ejxmjz));
                    //资金总额yearMoney
                    infoBaseProject.setYearMoney(ejxmjz1);
                }
                for (int k = i; k <= i; k++) {
                    //区域
                    if (list2.get(k + 2) != null) {
                        Object qu = list2.get(k + 2);
                        infoBaseProject.setAttributionArea(qu.toString());
                    }
                }
            }
            //把一级项目编号存储到二级项目中
            Long id = infoBaseProjectMapper.selectInfoBaseProjectByIds(yjxmmc);
            infoBaseProject.setParentId(id);
            infoBaseProjectMapper.insertInfoBaseProject(infoBaseProject);
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<InfoBaseProject> importExcel(MultipartFile file) throws Exception {

        if (file.isEmpty()) {
            System.out.println("文件为空！");
            throw new RuntimeException("文件为空！");
        }
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }

        ExcelReader reader = cn.hutool.poi.excel.ExcelUtil.getReader(inputStream); //指定输入流


        // 读取每一行到最后一行数据
        List<List<Object>> read = reader.read(0, reader.getRowCount(), true);
        //存数据到实体类（项目表）
        //一级项目相关信息
        InfoBaseProject infoBaseProject = new InfoBaseProject();

        //统计表（父项目表里的东西存进）
        InfoBaseProjectStatist infoBaseProjectStatist = new InfoBaseProjectStatist();

        for (int i = 0; i < 5; i++) {
            //行
            List<Object> objects = read.get(i);
            if (!objects.isEmpty()) {
                //判断第几行获取数据
                if (i == 0) {
                    //第一行
                    Object ejxmmc = objects.get(0);
                    //将一级项目名称存到表中
                    infoBaseProject.setProjectName(ejxmmc.toString());
                    infoBaseProject.setWorkCompany("甘肃省");
                    /*String deptName= String.valueOf(ejxmmc);
                    if(deptName.indexOf("甘肃省")!=-1){

                    }*/

                } else if (i == 1) {
                    //第二行数据  市州县区、单位   小计（判断他们）
                    Object szxq = objects.get(0); //市州县区、单位
                    Object xj = objects.get(1); //小计
                    if ("".equals(szxq) || "".equals(xj)) {
                        throw new NullPointerException("文件为空！");
                    }
                    //判断
                    if (!"市州县区、单位".equals(szxq.toString()) && !"小计".equals(xj.toString())) {
                        throw new RuntimeException("文件模板错误!");
                    }
                } else if (i == 2) {
                    //第三行数据
                    Object zyzj = objects.get(1); //中央资金合计
                    if (!"".equals(zyzj)) {
                        BigDecimal zyzj1 = new BigDecimal(String.valueOf(zyzj));
                        infoBaseProject.setCentralFund(zyzj1);
                    }

                } else if (i == 3) {
                    //第四行数据
                    Object sjzj = objects.get(1); //省级资金合计
                    if (sjzj != "") {
                        BigDecimal sjzj1 = new BigDecimal(String.valueOf(sjzj));
                        infoBaseProject.setProvincialFunds(sjzj1);
                    }
                } else if (i == 4) {
                    //第五行数据
                    Object hj = objects.get(1); //合计
                    if (hj != "") {
                        BigDecimal hj1 = new BigDecimal(String.valueOf(hj));
                        infoBaseProject.setTotalFunds(hj1);
                    }
                }
            }
        }
        //将一级项目相关信息存进表中
        Object loginUser = SecurityUtils.getLoginUser().getUser().getUserName();
        infoBaseProject.setCreateBy(loginUser.toString());
        infoBaseProject.setCreateByTime(DateUtils.getNowDate());
        Calendar date = Calendar.getInstance();
        String year = String.valueOf(date.get(Calendar.YEAR));
        infoBaseProject.setYear(year);
        infoBaseProjectMapper.insertInfoBaseProject(infoBaseProject);
        Long id = infoBaseProject.getId();
        infoBaseProjectStatist.setBaseProjectId(id);
        Long pid = infoBaseProject.getParentId();
        infoBaseProjectStatist.setBaseProjectParentId(pid);
        String name = infoBaseProject.getProjectName();
        infoBaseProjectStatist.setBaseProjectName(name);
        String workComoany = infoBaseProject.getWorkCompany();
        SysDept dept = sysDeptMapper.selectDeptListsss(workComoany);
        if (dept != null) {
            Long deptid = dept.getDeptId();
            String deptname = dept.getDeptName();
            infoBaseProjectStatist.setDeptId(deptid);
            infoBaseProjectStatist.setDeptName(deptname);
        } else {
            infoBaseProjectStatist.setDeptName(workComoany);
        }

        BeanUtils.copyProperties(infoBaseProject, infoBaseProjectStatist);
        infoBaseProjectStatistMapper.insertInfoBaseProjectStatist(infoBaseProjectStatist);
        //保存二级项目信息
        this.saveSecondProject(reader, id);
        //查询二级项目信息
        InfoBaseProject project = new InfoBaseProject();
        project.setParentId(id);
        List<InfoBaseProject> projectInfoList = infoBaseProjectMapper.selectInfoBaseProjectByParentId(project);
        projectInfoList.add(0, infoBaseProject);
        return projectInfoList;
    }

    /**
     * 资金文件解析二级项目信息
     *
     * @param reader
     * @param id
     * @throws Exception
     */
    public void saveSecondProject(ExcelReader reader, Long id) throws Exception {

        //获取行数
        int rowCount = reader.getRowCount();
        //获取列数
        int columnCount = reader.getColumnCount();
        List<SysDept> sysDeptList = sysDeptMapper.selectDeptList(new SysDept());
        for (int i = 3; i < columnCount; i++) {
            Object projectName = reader.readCellValue(i, 1);
            if (null != projectName && StringUtils.isNotEmpty(projectName.toString())) {
                List<InfoBaseProject> projectInfoList = new ArrayList<>();
                List<InfoBaseProjectStatist> projectStatistInfoList = new ArrayList<>();
                for (int j = 2; j < rowCount; j++) {
                    //二级项目相关信息
                    InfoBaseProject infoBaseProject1 = new InfoBaseProject();
                    //统计表（父项目表里的东西存进）
                    InfoBaseProjectStatist infoBaseProjectStatist1 = new InfoBaseProjectStatist();
                    Object area = reader.readCellValue(2, j + 3);
                    String area1 = String.valueOf(area);
                    if (area1.indexOf("合计") == -1 && area1.indexOf("注") == -1) {
                        //去部门表里查
                        List<SysDept> deptList = sysDeptList.stream().filter(s -> s.getDeptName().equals(area)).collect(Collectors.toList());
                        //SysDept sysDept = sysDeptMapper.selectDeptLists(area);
                        //校验
                        if (deptList.size() > 0) {
                            Long deptId = deptList.get(0).getDeptId();
                            String deptName = deptList.get(0).getDeptName();

                            infoBaseProjectStatist1.setDeptId(deptId);
                            infoBaseProjectStatist1.setDeptName(deptName);
                        } else {
                            if (area != null) {
                                infoBaseProjectStatist1.setDeptName(area.toString());
                            }
                        }
                        if (area != null && StringUtils.isNotEmpty(area.toString())) {
                           /* //获取中央资金
                            Object zy = reader.readCellValue(i, 2);
                            //省级
                            Object sj = reader.readCellValue(i, 3);
                            //合计
                            Object hj = reader.readCellValue(i, 4);*/
                            //资金额
                            Object zj = reader.readCellValue(i, j + 3);

                         /*   if (!"".equals(zy) && StringUtils.isNotEmpty(zy.toString())) {
                                BigDecimal zyzj3 = new BigDecimal(String.valueOf(zy));
                                infoBaseProject1.setCentralFund(zyzj3);
                            }
                            if (!"".equals(sj) && StringUtils.isNotEmpty(sj.toString())) {
                                BigDecimal sjzj3 = new BigDecimal(String.valueOf(sj));
                                infoBaseProject1.setProvincialFunds(sjzj3);
                            }
                            if (!"".equals(hj) && StringUtils.isNotEmpty(hj.toString())) {
                                BigDecimal hj3 = new BigDecimal(String.valueOf(hj));
//                            infoBaseProject1.setTotalFunds(hj3);
                            }*/


                            if (ObjectUtil.isNotEmpty(zj)) {

                                BigDecimal zyzj3 = new BigDecimal("0.0000");
                                infoBaseProject1.setCentralFund(zyzj3);
                                BigDecimal hj3 = new BigDecimal("0.0000");
                                infoBaseProject1.setOtherFund(hj3);
                                BigDecimal sjzj3 = new BigDecimal("0.0000");
                                infoBaseProject1.setProvincialFunds(sjzj3);

                                BigDecimal zj1 = new BigDecimal(String.valueOf(zj));
                                infoBaseProject1.setTotalFunds(zj1);

                                infoBaseProject1.setProjectName(projectName.toString());//项目名称
                                infoBaseProject1.setWorkCompany(area.toString());//省市区县
                                //将二级项目信息存进表中
                                infoBaseProject1.setParentId(id);
                                infoBaseProject1.setYear(Calendar.getInstance().get(Calendar.YEAR) + "");
                                infoBaseProject1.setCreateByTime(DateUtils.getNowDate());
                                infoBaseProject1.setIsHandAdd(0);
                                //将保存的信息存入list，后续进行批量插入
                                projectInfoList.add(infoBaseProject1);
                                // infoBaseProjectMapper.insertInfoBaseProject(infoBaseProject1);
                                infoBaseProjectStatist1.setBaseProjectId(infoBaseProject1.getId());
                                infoBaseProjectStatist1.setBaseProjectParentId(infoBaseProject1.getParentId());
                                infoBaseProjectStatist1.setBaseProjectName(infoBaseProject1.getProjectName());
                                BeanUtils.copyProperties(infoBaseProject1, infoBaseProjectStatist1);
                                //将统计数据加入list，后续批量插入
                                projectStatistInfoList.add(infoBaseProjectStatist1);
                                //infoBaseProjectStatistMapper.insertInfoBaseProjectStatist(infoBaseProjectStatist1);
                            }
                        }
                    }

                }
                //进行数据的批量插入
                infoBaseProjectMapper.batchInsertBaseProject(projectInfoList);
                //统计表进行批量数据插入
                infoBaseProjectStatistMapper.batchInsertProjectStatist(projectStatistInfoList);
            }
        }
    }


    @Override
    public List<InfoBaseProject> selectInfoBaseProjectListByDepartmentId(InfoBaseProject infoBaseProject) {
        return infoBaseProjectMapper.selectInfoBaseProjectListByDepartmentId(infoBaseProject);
    }

    @Override
    public List<InfoBaseProject> selectInfoBaseProject(Long id, String date) {
        return infoBaseProjectMapper.selectInfoBaseProjectLists(id, date);
    }

    @Override
    public List<InfoBaseProject> selectInfoBaseProjectByIds(Long id) {
        return infoBaseProjectMapper.selectInfoBaseProjectByIdss(id);
    }

    //获取每个地区的一级二级数量
    @Override
    public List<TjProjectVo> selectInfoBaseProjectss() {
        SysDept sysDept = sysDeptMapper.selectDeptListsss("甘肃省");
        List<TjProjectVo> tjProjectVo = new ArrayList<>();
        //获取所有市
        List<SysDept> list = sysDeptMapper.selectDeptLitss(sysDept.getDeptId());
        TjProjectVo tjProjectVo1 = new TjProjectVo();
        //查所有一级项目数
        Integer yj = infoBaseProjectMapper.selectProject();
        tjProjectVo1.setYjzs(yj);
        //查所有二级项目数
        Integer ej = infoBaseProjectMapper.selectInfo();
        tjProjectVo1.setEjzs(ej);
        //总数
        Integer zs = yj + ej;
        tjProjectVo1.setZs(zs);

        tjProjectVo.add(tjProjectVo1);
        //查所有项目
        for (int i1 = 0; i1 < list.size(); i1++) {
            Long ids = list.get(i1).getDeptId();
            String name = list.get(i1).getDeptName();
            List<String> xmy = new ArrayList<>();
            List<InfoBaseProject> infoBaseProjects2 = infoBaseProjectMapper.selectInfoBaseProjectys(name);
            if (infoBaseProjects2.size() > 0) {
                for (int i = 0; i < infoBaseProjects2.size(); i++) {
                    xmy.add(infoBaseProjects2.get(i).getProjectName());
                }
            }
            //获取市下的县区
            if (i1 > 0) {
                List<SysDept> sysDepts = sysDeptMapper.selectDeptLitss(ids);
                List<String> xm = new ArrayList<>();
                for (int i = 0; i < sysDepts.size(); i++) {
                    String workcompany = sysDepts.get(i).getDeptName();
                    //查询到兰州市下的县区的所有项目(包括兰州市）
                    List<InfoBaseProject> infoBaseProjectslist = infoBaseProjectMapper.selectInfoBaseProject(workcompany);
                    if (infoBaseProjectslist.size() > 0) {
                        for (int j = 0; j < infoBaseProjectslist.size(); j++) {
                            xm.add(infoBaseProjectslist.get(j).getProjectName());
                        }
                    }
                }
                Integer yjx = 0;
                TjProjectVo tjProjectVo2 = new TjProjectVo();
                tjProjectVo2.setDq(name);
                yjx = xmy.size();
                tjProjectVo2.setYj(yjx);
                tjProjectVo2.setEj(xm.size());
                ej = xm.size();
                zs = yjx + ej;
                tjProjectVo2.setZs(zs);
                tjProjectVo.add(tjProjectVo2);
            }
        }
        return tjProjectVo;
    }

    //获取每个地区的一级二级数量
    @Override
    public List<TjProjectVo> selectInfoProjects() {
        SysDept sysDept = sysDeptMapper.selectDeptListsss("甘肃省");
        //查询各地区一二级项目数
        List<TjProjectVo> projectVos = infoBaseProjectStatistMapper.selectProjectInfo(sysDept.getDeptId());
        //查所有一级项目数
        Integer yj = infoBaseProjectMapper.selectProject();
        TjProjectVo projectVo = new TjProjectVo();
        projectVo.setYjzs(yj);
        //获取二级项目数
        Integer second = projectVos.stream().collect(Collectors.summingInt(TjProjectVo::getEj));
        projectVo.setEjzs(second);
        //总数
        projectVo.setZs(yj + second);
        projectVos.add(0, projectVo);
        return projectVos;
    }

    @Override
    public void getInfo(InfoBaseProject infoBaseProject) {
        //查询执行数
        InfoBaseProject infoProject = infoBaseProjectMapper.selectTotalFundsExecute(infoBaseProject.getId());
        if (ObjectUtil.isEmpty(infoProject)) {
            infoProject = new InfoBaseProject();
            infoProject.setTotalEx("0");
            infoProject.setCenEx("0");
            infoProject.setProEx("0");
            infoProject.setOthEx("0");
        }
        //计算执行率    new DecimalFormat("0.00").format(pi)
        BigDecimal totalRa = BigDecimal.valueOf(0);
        BigDecimal cenRa = BigDecimal.valueOf(0);
        BigDecimal proRa = BigDecimal.valueOf(0);
        BigDecimal othRa = BigDecimal.valueOf(0);
        if (ObjectUtil.isNotEmpty(infoBaseProject.getTotalFunds()) && infoBaseProject.getTotalFunds().compareTo(BigDecimal.valueOf(0)) == 1) {
            totalRa = new BigDecimal(infoProject.getTotalEx()).divide(infoBaseProject.getTotalFunds(), 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
        }
        if (ObjectUtil.isNotEmpty(infoBaseProject.getCentralFund()) && infoBaseProject.getCentralFund().compareTo(BigDecimal.valueOf(0)) == 1) {
            cenRa = new BigDecimal(infoProject.getCenEx()).divide(infoBaseProject.getCentralFund(), 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
        }
        if (ObjectUtil.isNotEmpty(infoBaseProject.getProvincialFunds()) && infoBaseProject.getProvincialFunds().compareTo(BigDecimal.valueOf(0)) == 1) {
            proRa = new BigDecimal(infoProject.getProEx()).divide(infoBaseProject.getProvincialFunds(), 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
        }
        if (ObjectUtil.isNotEmpty(infoBaseProject.getOtherFund()) && infoBaseProject.getOtherFund().compareTo(BigDecimal.valueOf(0)) == 1) {
            othRa = new BigDecimal(infoProject.getOthEx()).divide(infoBaseProject.getOtherFund(), 2, BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100));
        }
        infoBaseProject.setCenRa(cenRa.toString());
        infoBaseProject.setProRa(proRa.toString());
        infoBaseProject.setOthRa(othRa.toString());
        infoBaseProject.setTotalRa(totalRa.toString());
        infoBaseProject.setTotalEx(infoProject.getTotalEx());
        infoBaseProject.setCenEx(infoProject.getCenEx());
        infoBaseProject.setProEx(infoProject.getProEx());
        infoBaseProject.setOthEx(infoProject.getOthEx());
    }

    @Override
    public Map<String, Object> getHomeStatisticsAmount(Long deptId) {
        Map<String, Object> mapList = new HashMap<>();
        List<Map<String, Object>> homeStatistics = infoBaseProjectMapper.selectHomeStatisticsAmount(deptId);
        mapList.put("homeStatisticsAmountInfo", homeStatistics);
        BigDecimal total = new BigDecimal(0);
        for (Map<String, Object> map : homeStatistics) {
            total = total.add(new BigDecimal(map.get("totalFunds").toString()));
        }
        mapList.put("totalAmount", total);
        return mapList;
    }

    @Override
    public List<Map<String, Object>> getSecondProjectList(BigInteger projectId) {
        return infoBaseProjectMapper.selectSecondProjectList(projectId);
    }

    @Override
    public List<InfoBaseProject> getProjectDepartmentList(BigInteger parentId, String projectName) {
        return infoBaseProjectMapper.selectProjectDepartmentList(parentId, projectName);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handAddProject(InfoBaseProject infoBaseProject) {
        //项目库添加一级项目
        infoBaseProject.setCreateBy("sjc");
        infoBaseProject.setCreateByTime(DateUtils.getNowDate());
        Calendar date = Calendar.getInstance();
        String year = String.valueOf(date.get(Calendar.YEAR));
        infoBaseProject.setYear(year);
        infoBaseProject.setIsHandAdd(1);
        infoBaseProjectMapper.insertInfoBaseProject(infoBaseProject);
        //统计库添加一级项目
        InfoBaseProjectStatist infoBaseProjectStatist = new InfoBaseProjectStatist();
        Long id = infoBaseProject.getId();
        infoBaseProjectStatist.setBaseProjectId(id);
        String name = infoBaseProject.getProjectName();
        infoBaseProjectStatist.setBaseProjectName(name);
        String workComoany = infoBaseProject.getWorkCompany();
        SysDept dept = sysDeptMapper.selectDeptListsss(workComoany);
        if (dept != null) {
            Long deptid = dept.getDeptId();
            String deptname = dept.getDeptName();
            infoBaseProjectStatist.setDeptId(deptid);
            infoBaseProjectStatist.setDeptName(deptname);
        } else {
            infoBaseProjectStatist.setDeptName(workComoany);
        }
        BeanUtils.copyProperties(infoBaseProject, infoBaseProjectStatist);
        infoBaseProjectStatistMapper.insertInfoBaseProjectStatist(infoBaseProjectStatist);
        //项目库添加二级项目
        InfoBaseProject infoBaseProjectOne = new InfoBaseProject();
        BeanUtils.copyProperties(infoBaseProject, infoBaseProjectOne);
        infoBaseProjectOne.setParentId(infoBaseProject.getId());
        infoBaseProjectOne.setCreateBy(null);
        infoBaseProjectMapper.insertInfoBaseProject(infoBaseProjectOne);
        //统计表增加二级项目
        InfoBaseProjectStatist infoBaseProjectStatistOne = new InfoBaseProjectStatist();
        BeanUtils.copyProperties(infoBaseProjectStatist, infoBaseProjectStatistOne);
        infoBaseProjectStatistOne.setBaseProjectParentId(infoBaseProjectStatist.getId());
        infoBaseProjectStatistOne.setId(null);
        infoBaseProjectStatistOne.setBaseProjectId(null);
        infoBaseProjectStatistMapper.insertInfoBaseProjectStatist(infoBaseProjectStatistOne);
    }

    @Override
    public String getParentProjectName(Long projectId) {
        return infoBaseProjectMapper.selectParentProjectName(projectId);
    }

    /**
     * 提交
     * 审核状态 0 未提交 1 待审核 2一级审核通过 3 终审通过
     *
     * @param infoBaseProject
     * @return
     */
    @Override
    public String submitProject(InfoBaseProject infoBaseProject) {
        InfoBaseProject infoBaseProject1 = infoBaseProjectMapper.selectInfoBaseProjectById(infoBaseProject.getId());
        //拼接部门层级
        infoBaseProject.setAncestors(infoBaseProject1.getAncestors() + "," + infoBaseProject.getAncestors());
        //修改审核状态
        if ("0".equals(infoBaseProject1.getProjectStstus())) {
            infoBaseProject.setProjectStstus("1");
        }
        int i = infoBaseProjectMapper.updateInfoBaseProject(infoBaseProject);
        if (i == 1) {
            return "提交成功！";
        }
        return "提交失败!";
    }

    /**
     * 审核
     *
     * @param infoBaseProject
     * @return 0 待提交  1待审核 2 待审核 3审核通过 3审核不通过
     */
    @Override
    public AjaxResult examineProject(InfoBaseProject infoBaseProject) {
        InfoBaseProject infoBaseProject1 = infoBaseProjectMapper.selectInfoBaseProjectById(infoBaseProject.getId());
        //如果是终审添加数据
        if ("100".equals(infoBaseProject.getAncestors()) || org.apache.commons.lang3.StringUtils.isEmpty(infoBaseProject.getAncestors())){
            if ("3".equals(infoBaseProject.getProjectStstus())) {
                if (infoBaseProject.getAncestors() != null){
                    return AjaxResult.error("终审无需选择上级审核单位！");
                }
                if (!StringUtils.isNotNull(infoBaseProject1.getProjectNodeStatus())) {
                    infoBaseProject.setProjectNodeStatus(SecurityUtils.getDeptId().toString());
                }
                infoBaseProject.setProjectNodeStatus(infoBaseProject1.getProjectNodeStatus() + "," + SecurityUtils.getDeptId());
                infoBaseProject.setAncestors(infoBaseProject1.getAncestors() + "," + infoBaseProject.getAncestors());
                //像目标表添加数据并修改状态
                //项目阶段（默认0：储备项目，1：年度项目）
//            if (infoBaseProject1.getIsXg() == 1){
//                //extracted(infoBaseProject1);
//                infoBaseProject.setImplementStatus(1);
//            }
                infoBaseProjectMapper.updateInfoBaseProject(infoBaseProject);
                return AjaxResult.success("终审通过！");
            }
            return AjaxResult.error("请选择正确的上级单位！");
        }
        if ("1".equals(infoBaseProject.getProjectStstus())) {
            infoBaseProject.setProjectStstus("2");

            infoBaseProjectMapper.updateInfoBaseProject(infoBaseProject);
            return AjaxResult.success("提交成功！");
        }
        //退回
        if ("4".equals(infoBaseProject.getProjectStstus())) {
            //修改状态并且像目标表添加数据
            infoBaseProject.setProjectNodeStatus("000");
            infoBaseProjectMapper.updateInfoBaseProject(infoBaseProject);
            return AjaxResult.success("退回成功！");
        }
        if ("2".equals(infoBaseProject.getProjectStstus()) && infoBaseProject.getAncestors() != null) {
            if (infoBaseProject1.getProjectNodeStatus() == null) {
                infoBaseProject.setProjectNodeStatus(SecurityUtils.getDeptId().toString());
            }
            infoBaseProject.setProjectNodeStatus(infoBaseProject1.getProjectNodeStatus() + "," + SecurityUtils.getDeptId());
            infoBaseProject.setAncestors(infoBaseProject1.getAncestors() + ","+infoBaseProject.getAncestors());
            infoBaseProjectMapper.updateInfoBaseProject(infoBaseProject);
            return AjaxResult.success("审核通过！");
        } else {
            return AjaxResult.error("请选择上级审核单位!");
        }
    }

    //像目标管理中添加数据
    private int extracted(InfoBaseProject infoBaseProject1) {
        InfoProjectTarget infoProjectTarget = new InfoProjectTarget();
//        infoProjectTarget.setProjectName(infoBaseProject1.getProjectName());
//        infoProjectTarget.setBaseProjectId(infoBaseProject1.getId());
//        //存项目库实施单位
////            String ancestors = infoBaseProject1.getAncestors();
////            String[] split = ancestors.split(",");
////            String s = split[split.length-1];
//        //终审单位id写死
//        infoProjectTarget.setDeptId(623130l);
//        infoProjectTarget.setReleaseDepartmentId(Long.valueOf(infoBaseProject1.getWorkCompany()));
//        infoProjectTarget.setExamineStatus(0);
//        infoProjectTarget.setWorkCompany(sysDeptMapper.selectDeptById(Long.valueOf(infoBaseProject1.getWorkCompany())).getDeptName());
//        //主管单位
//        infoProjectTarget.setDepartmentId(infoBaseProject1.getDepartmentId());
//        infoProjectTarget.setDepartmentName(sysDeptMapper.selectDeptById(infoBaseProject1.getDepartmentId()).getDeptName());
//        infoProjectTarget.setCreateByTime(infoBaseProject1.getCreateByTime());
//        infoProjectTarget.setEndTime(infoBaseProject1.getEndTime());
//        infoProjectTarget.setCreateTime(DateUtils.getNowDate());
//        infoProjectTarget.setProjectAttribute(infoBaseProject1.getProjectAttribute());
        InfoProjectTarget extracted = extracted(infoBaseProject1, infoProjectTarget);
        return infoProjectTargetMapper.insertInfoProjectTarget(extracted);
    }

    /**
     * 填报查询
     *
     * @param infoBaseProject
     * @return
     */
    @Override
    public List<InfoBaseProject> selectInfoBaseProjectsTb(InfoBaseProject infoBaseProject) {
        //根据实施单位查询当前部门
        infoBaseProject.setWorkCompany(SecurityUtils.getDeptId().toString());
        List<InfoBaseProject> infoBaseProjects = infoBaseProjectMapper.selectInfoBaseProjectList(infoBaseProject);
        //进行处理
        return infoBaseProjects;
    }

    /**
     * 审核查询
     *
     * @param infoBaseProject
     * @return
     */
    @Override
    public List<InfoBaseProject> selectInfoBaseProjectsSh(InfoBaseProject infoBaseProject) {
        //当前部门id
        String deptId = String.valueOf(SecurityUtils.getDeptId());
        //查所有
        List<InfoBaseProject> infoBaseProjects = infoBaseProjectMapper.selectInfoBaseProjectList(new InfoBaseProject());
        List<InfoBaseProject> collect = infoBaseProjects.stream()
                .filter(x -> x.getAncestors().contains(deptId)).collect(Collectors.toList());
        for (InfoBaseProject baseProject : collect) {
            if (StringUtils.isNotNull(baseProject.getProjectNodeStatus())) {
                if (baseProject.getProjectNodeStatus().contains(deptId)) {
                    baseProject.setReleaseStatus(1);
                } else {
                    baseProject.setReleaseStatus(0);
                }
            } else {
                baseProject.setReleaseStatus(0);
            }
        }
        for (InfoBaseProject baseProject : collect) {
            baseProject.setWorkCompanyName(sysDeptMapper.selectDeptById(Long.valueOf(baseProject.getWorkCompany())).getDeptName());
            baseProject.setDepartmentName(sysDeptMapper.selectDeptById(baseProject.getDepartmentId()).getDeptName());
        }
        return collect;
    }

    @Override
    public HomePVO selectHomePage() {
        return infoBaseProjectMapper.selectHomePage();
    }

    @Override
    public List<HomePVO> selecttypePercentage() {
        List<HomePVO> homePVO = infoBaseProjectMapper.selecttypePercentage();
        long sum1 = homePVO.stream().mapToLong(HomePVO::getTypeSum).sum();
        BigDecimal sum = new BigDecimal(sum1);
        int i = 1;
        for (HomePVO pvo : homePVO) {
            BigDecimal bigDecimal = new BigDecimal(pvo.getTypeSum());
            BigDecimal divide = bigDecimal.divide(sum, 2, BigDecimal.ROUND_HALF_UP);
            pvo.setPercentage(divide.doubleValue());
            pvo.setMonthly(i);
            i++;
        }
        return homePVO;
    }

    @Override
    public List<HomePVO> selectmonthlySumAndTotal(String year) {

        ArrayList<Integer> integers = new ArrayList<>();
        List<HomePVO> homePVOS = infoBaseProjectMapper.selectmonthlySumAndTotal(year);
        List<Integer> collect = homePVOS.stream().map(HomePVO::getMonthly).collect(Collectors.toList());
        for (int i = 1; i <= 12; i++) {
            HomePVO homePVO1 = new HomePVO();
            if (!collect.contains(i)) {
                homePVO1.setMonthly(i);
                homePVO1.setProjectSum(0l);
                homePVO1.setTotalFund(new BigDecimal("0.00"));
                homePVOS.add(homePVO1);
            }
        }
        List<HomePVO> collect1 = homePVOS.stream().sorted(Comparator.comparing(HomePVO::getMonthly)).collect(Collectors.toList());
        return collect1;
    }

    @Override
    public List<HomePVO> selectprojectType(String year) {
        //查市名称
        List<HomePVO> homePVO  = infoBaseProjectMapper.selectDeptOrs();
        for (HomePVO pvo : homePVO) {
            //查寻市的子
            String deptId = pvo.getDeptId().toString();
            List<HomePVO> homePVO1 = infoBaseProjectMapper.selectDeptCh(deptId);
            if (homePVO1.size() > 0){
                //获取子集id
                List<Long> collect = homePVO1.stream().map(HomePVO::getDeptId).collect(Collectors.toList());
                //转换字符串
                String join = String.join(",", collect.stream().map(String::valueOf).collect(Collectors.toList()));
                //查询所有目标
                List<InfoProjectTarget> targets = infoProjectTargetMapper.selectExamineInfoProjectTargetList2(year);
                //过滤
                List<InfoProjectTarget> collect1 = targets.stream().filter(x -> join.contains(x.getReleaseDepartmentId().toString())).collect(Collectors.toList());
                BigDecimal reduce = collect1.stream().map(InfoProjectTarget::getTotalFunds).reduce(BigDecimal.ZERO, BigDecimal::add);
//                List<BigDecimal> collect2 = collect1.stream().map(InfoProjectTarget::getTotalFunds).collect(Collectors.toList());
                pvo.setTotalFund(reduce);
            }
        }
        for (HomePVO pvo : homePVO) {
            if (!StringUtils.isNotNull(pvo.getTotalFund())){
                pvo.setTotalFund(new BigDecimal("0.00"));
            }
            if (pvo.getDeptId() == 394 || pvo.getDeptId() == 395){
                String substring = pvo.getDeptName().substring(0, 2);
                pvo.setDeptName(substring);
            }else {
                String newName = pvo.getDeptName().replace("市", "");
                pvo.setDeptName(newName);
            }
        }
        return homePVO;
    }

    @Override
    public AjaxResult implementProject(InfoBaseProject infoBaseProject) {
        InfoBaseProject infoBaseProject1 = infoBaseProjectMapper.selectInfoBaseProjectById(infoBaseProject.getId());
        int extracted = extracted(infoBaseProject1);
        if (extracted == 1){
            //修改状态为已实施
            infoBaseProject.setImplementStatus(1);
            infoBaseProjectMapper.updateInfoBaseProject(infoBaseProject);
            return AjaxResult.success("实施成功!");
        }else {
            return AjaxResult.error("实施失败！");
        }
    }


    @Override
    public List<StatistDeptVo> selectInfoStatistDeept(InfoProjectTarget projectTarget) {
        String start = "";
        String end = "";
        if (projectTarget.getCreateByTime() != null){
            start = DateFormatUtils.format(projectTarget.getCreateByTime(), "yyyy-MM-dd");
            end = DateFormatUtils.format(projectTarget.getEndTime(), "yyyy-MM-dd");
        }
        return infoProjectTargetMapper.selectInfoStatistDeept(start,end);
    }

    /**
     * (0待主管审核 1 待财政审核 2通过3退回)
     * @param infoProjectTargetAdjust
     * @return
     */
    @Override
    public AjaxResult applyAdjust(InfoProjectTargetAdjust infoProjectTargetAdjust) {
        InfoProjectTarget infoProjectTarget = infoProjectTargetMapper.selectInfoProjectTargetByIdss(infoProjectTargetAdjust.getBaseProjectId());
        if (infoProjectTargetAdjust.getIsAdjustTarget() == 1 && StringUtils.isNull(infoProjectTarget)){
            return AjaxResult.error("该项目未开展目标！");
        }
        if(infoProjectTargetAdjust.getIsAdjustTarget() == 1 && infoProjectTarget.getExamineStatus() != 4 ){
            return AjaxResult.error("该项目目标未审核通过！");
        }
        if (infoProjectTarget!=null){
            infoProjectTargetAdjust.setBaseProjectTargetId(infoProjectTarget.getId());
        }
        infoProjectTargetAdjust.setCreateTime(DateUtils.getNowDate());
        infoProjectTargetAdjustMapper.insertInfoProjectTargetAdjust(infoProjectTargetAdjust);
        //修改项目库中的isXg表示已申请年中调整
        InfoBaseProject infoBaseProject = infoBaseProjectMapper.selectInfoBaseProjectById(infoProjectTargetAdjust.getBaseProjectId());
        infoBaseProject.setIsXg(1);
        if (!infoBaseProject.getAncestors().contains(infoBaseProject.getDepartmentId().toString())) {
            infoBaseProject.setAncestors(infoBaseProject.getAncestors() +","+infoBaseProject.getDepartmentId());

        }
        infoBaseProjectMapper.updateInfoBaseProject(infoBaseProject);
        return AjaxResult.success("提交成功！");
    }

    //0待主管审核 1 待财政审核 2待调整 3退回
    @Override
    @Transactional
    public AjaxResult examineAdjust(InfoProjectTargetAdjust infoProjectTargetAdjust) {
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        List<String> collect = sysUser.getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        InfoProjectTargetAdjust infoProjectTargetAdjust1 = infoProjectTargetAdjustMapper.selectInfoProjectTargetAdjustById(infoProjectTargetAdjust.getId());
        if (1==infoProjectTargetAdjust.getAdjustStatus()){
//            if (StringUtils.isNotNull(infoProjectTargetAdjust1.geas)){
//                infoProjectTargetAdjust.setAdjustNode(SecurityUtils.getDeptId().toString());
//            }else {
//                infoProjectTargetAdjust.setAdjustNode(infoProjectTargetAdjust1.getAdjustNode()+","+SecurityUtils.getDeptId());
//            }
            infoProjectTargetAdjustMapper.updateInfoProjectTargetAdjust(infoProjectTargetAdjust);
            return AjaxResult.success("审核成功！");
        }
        if (2==infoProjectTargetAdjust.getAdjustStatus() && !collect.contains("sjc")){
            return AjaxResult.error("系统错误！");
        }
        //终审
        if (2==infoProjectTargetAdjust.getAdjustStatus()){
            infoProjectTargetAdjustMapper.updateInfoProjectTargetAdjust(infoProjectTargetAdjust);
            //新增一条目标
            if (infoProjectTargetAdjust1.getIsAdjustTarget() == 1) {
                AdjustTargetVo adjustTargetVo = new AdjustTargetVo();
                InfoProjectTarget infoProjectTarget = infoProjectTargetMapper.selectInfoProjectTargetByProjectId(infoProjectTargetAdjust1.getBaseProjectId());
                //目标主题
                adjustTargetVo.setInfoProjectTarget(infoProjectTarget);
                //目标指标
                List<InfoProjectTargetIndex> infoProjectTargetIndices = infoProjectTargetIndexMapper.selectInfoProjectTargetIndexByProjectId(infoProjectTarget.getId());
                if (!infoProjectTargetIndices.isEmpty()){
                    adjustTargetVo.setIndexList(infoProjectTargetIndices);
                }
                //目标附件
                InfoProjectCapitalAnnex infoProjectCapitalAnnex = new InfoProjectCapitalAnnex();
                infoProjectCapitalAnnex.setProjectId(infoProjectTarget.getId());
                List<InfoProjectCapitalAnnex> infoProjectCapitalAnnexes = infoProjectCapitalAnnexService.selectInfoProjectCapitalAnnexList(infoProjectCapitalAnnex);
                adjustTargetVo.setAnnexList(infoProjectCapitalAnnexes);
                //调用新增方法
                Long newTargetId = infoProjectTargetService.adjustProjectTarget(adjustTargetVo);
                infoProjectTargetAdjust.setBaseProjectTargetNewId(newTargetId);
                infoProjectTargetAdjustMapper.updateInfoProjectTargetAdjust(infoProjectTargetAdjust);
            }
            //暂存表新增
            if (infoProjectTargetAdjust1.getIsAdjustProject() == 1){
                InfoBaseProject infoBaseProject = infoBaseProjectMapper.selectInfoBaseProjectById(infoProjectTargetAdjust1.getBaseProjectId());
                adjustProject(infoBaseProject);
            }
            return AjaxResult.success("审核成功！");
        }
        if (3==infoProjectTargetAdjust.getAdjustStatus()){
            infoProjectTargetAdjustMapper.updateInfoProjectTargetAdjust(infoProjectTargetAdjust);
            return AjaxResult.success("退回成功！");
        }
        return AjaxResult.error("系统错误！");
    }

    @Override
    public AjaxResult adjustProject(InfoBaseProject infoBaseProject) {
        updateStaging(infoBaseProject,1);
        //调整结束状态改为1
        InfoBaseProjectTargetStaging infoBaseProjectTargetStaging1 = infoBaseProjectTargetStagingMapper.selectInfoBaseProjectTargetStagingByProjectId(infoBaseProject.getId());
        InfoProjectTargetAdjust infoProjectTargetAdjust = infoProjectTargetAdjustMapper.selectInfoProjectTargetAdjustByProjectId(infoBaseProject.getId());
        infoProjectTargetAdjust.setBaseProjectStagingId(infoBaseProjectTargetStaging1.getId());
        infoProjectTargetAdjustMapper.updateInfoProjectTargetAdjust(infoProjectTargetAdjust);
        return AjaxResult.success("调整成功！");

    }

    @Override
    public AjaxResult examineAdjustProject(InfoBaseProject infoBaseProject) {
        InfoBaseProjectTargetStaging infoBaseProjectTargetStaging = new InfoBaseProjectTargetStaging();
        infoBaseProjectTargetStaging.setId(infoBaseProject.getStagingId());
        infoBaseProjectTargetStaging.setProjectAdjustStatus(infoBaseProject.getProjectAdjustStatus());

        //戴主管审核
        if (infoBaseProjectTargetStaging.getProjectAdjustStatus() == 1){
            updateStaging(infoBaseProject,2);
            infoBaseProjectTargetStagingMapper.updateInfoBaseProjectTargetStaging(infoBaseProjectTargetStaging);
            return AjaxResult.success("提交成功！");
        }
        if (infoBaseProjectTargetStaging.getProjectAdjustStatus() == 2){
            infoBaseProjectTargetStagingMapper.updateInfoBaseProjectTargetStaging(infoBaseProjectTargetStaging);
            return AjaxResult.success("审核成功！");
        }
        //终审通过，同步数据
        if (infoBaseProjectTargetStaging.getProjectAdjustStatus() == 3){
            infoBaseProjectTargetStagingMapper.updateInfoBaseProjectTargetStaging(infoBaseProjectTargetStaging);
            InfoBaseProjectTargetStaging infoBaseProjectTargetStaging1 = infoBaseProjectTargetStagingMapper.selectInfoBaseProjectTargetStagingById(infoBaseProject.getStagingId());
            InfoBaseProject infoBaseProject1 = new InfoBaseProject();
            BeanUtils.copyProperties(infoBaseProjectTargetStaging1,infoBaseProject1);
            infoBaseProject1.setId(infoBaseProjectTargetStaging1.getProjectBaseId());
            synchronousAllProject(infoBaseProject1);
            return AjaxResult.success("终审通过数据同步成功！");
        }
        if (infoBaseProjectTargetStaging.getProjectAdjustStatus() == 4){
            infoBaseProjectTargetStagingMapper.updateInfoBaseProjectTargetStaging(infoBaseProjectTargetStaging);
            return AjaxResult.success("退回成功！");
        }
        return AjaxResult.error();
    }

    public void updateStaging(InfoBaseProject infoBaseProject,Integer type){
        InfoBaseProjectTargetStaging infoBaseProjectTargetStaging = new InfoBaseProjectTargetStaging();
        infoBaseProjectTargetStaging.setProjectBaseId(infoBaseProject.getId());
        infoBaseProjectTargetStaging.setProjectAddress(infoBaseProject.getProjectAddress());
        infoBaseProjectTargetStaging.setProjectMoney(infoBaseProject.getProjectMoney());
        infoBaseProjectTargetStaging.setProjectContent(infoBaseProject.getProjectContent());
        infoBaseProjectTargetStaging.setProjectAttribute(infoBaseProject.getProjectAttribute());
        infoBaseProjectTargetStaging.setProjectName(infoBaseProject.getProjectName());
        infoBaseProjectTargetStaging.setCreateByTime(infoBaseProject.getCreateByTime());
        infoBaseProjectTargetStaging.setEndTime(infoBaseProject.getEndTime());
        infoBaseProjectTargetStaging.setProjectParam1(infoBaseProject.getProjectParam1());
        infoBaseProjectTargetStaging.setProjectParam2(infoBaseProject.getProjectParam2());
        infoBaseProjectTargetStaging.setProjectParam3(infoBaseProject.getProjectParam3());
        infoBaseProjectTargetStaging.setProjectParam4(infoBaseProject.getProjectParam4());
        infoBaseProjectTargetStaging.setDepartmentId(infoBaseProject.getDepartmentId());
        infoBaseProjectTargetStaging.setWorkCompany(infoBaseProject.getWorkCompany());
        infoBaseProjectTargetStaging.setProjectNode(infoBaseProject.getProjectNode());
        infoBaseProjectTargetStaging.setFundChannels(infoBaseProjectTargetStaging.getFundChannels());
        infoBaseProjectTargetStaging.setCapitalScale(infoBaseProjectTargetStaging.getCapitalScale());
        infoBaseProjectTargetStaging.setRemark(infoBaseProjectTargetStaging.getRemark());
        if (type == 1){
            infoBaseProjectTargetStagingMapper.insertInfoBaseProjectTargetStaging(infoBaseProjectTargetStaging);
        }
        if (type == 2){
            infoBaseProjectTargetStagingMapper.updateInfoBaseProjectTargetStaging(infoBaseProjectTargetStaging);
        }
    }



    /**
     * 同步所有模块项目信息
     * @param infoBaseProject
     * @return
     */
    @Transactional
    public AjaxResult synchronousAllProject(InfoBaseProject infoBaseProject) {
        //先修改项目库
//        infoBaseProject.setIsXg(2);
        infoBaseProjectMapper.updateInfoBaseProject(infoBaseProject);
        //同步所有模块
        InfoProjectTarget infoProjectTarget = infoProjectTargetMapper.selectInfoProjectTargetByIdss(infoBaseProject.getId());
        if (infoProjectTarget != null){
            InfoProjectTarget  infoProjectTarget1 =extracted(infoBaseProject, infoProjectTarget);
            infoProjectTargetMapper.updateInfoProjectTarget(infoProjectTarget1);
            InfoProjectTarget infoProjectTarget2 = infoProjectTargetMapper.selectInfoProjectTargetById(infoProjectTarget1.getId());
            //事前
            InfoBeforehandEvaluate infoBeforehandEvaluate = infoBeforehandEvaluateMapper.selectInfoBeforehandEvaluateTargetId(infoProjectTarget2.getId());
            if (infoBeforehandEvaluate != null){
                InfoBeforehandEvaluate infoBeforehandEvaluate1 = synchroBeforehand(infoBaseProject, infoBeforehandEvaluate);
                InfoProjectMonitor infoProjectMonitor = infoProjectMonitorMapper.selectInfoProjectMonitorByTargetId(infoProjectTarget2.getId());
                if (infoProjectMonitor != null){
                    infoProjectMonitor.setProjectStage(infoBeforehandEvaluate1.getProjectStage());
                    infoProjectMonitor.setProjectName(infoBeforehandEvaluate1.getProjectName());
                    infoProjectMonitorMapper.updateInfoProjectMonitor(infoProjectMonitor);
                    InfoProjectEvaluate infoProjectEvaluate = infoProjectEvaluateMapper.selectInfoProjectEvaluateByTargetId(infoProjectTarget2.getId());
                    if (infoProjectEvaluate != null){
                        infoProjectEvaluate.setProjectName(infoProjectTarget2.getProjectName());
                        infoProjectEvaluate.setProjectStage(infoBeforehandEvaluate1.getProjectStage());
                        infoProjectEvaluateMapper.updateInfoProjectEvaluate(infoProjectEvaluate);
                    }
                }
            }
            //监控

        }
        return AjaxResult.success();
    }

    //同步事前评估
    private InfoBeforehandEvaluate synchroBeforehand(InfoBaseProject infoBaseProject,InfoBeforehandEvaluate infoBeforehandEvaluate){


        infoBeforehandEvaluate.setProjectName(infoBaseProject.getProjectName());
        SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy/MM/dd");
        String format = dateFormat.format(infoBaseProject.getCreateByTime());
        String format1 = dateFormat.format(infoBaseProject.getEndTime());
        infoBeforehandEvaluate.setProjectStage(format +"-"+format1);
        infoBeforehandEvaluateMapper.updateInfoBeforehandEvaluate(infoBeforehandEvaluate);
        return infoBeforehandEvaluateMapper.selectInfoBeforehandEvaluateById(infoBeforehandEvaluate.getId());
    }

    private InfoProjectTarget extracted(InfoBaseProject infoBaseProject1, InfoProjectTarget infoProjectTarget) {
        infoProjectTarget.setProjectName(infoBaseProject1.getProjectName());
        infoProjectTarget.setBaseProjectId(infoBaseProject1.getId());
        //存项目库实施单位
//            String ancestors = infoBaseProject1.getAncestors();
//            String[] split = ancestors.split(",");
//            String s = split[split.length-1];
        //终审单位id写死
        infoProjectTarget.setDeptId(623131l);
        infoProjectTarget.setReleaseDepartmentId(Long.valueOf(infoBaseProject1.getWorkCompany()));
        infoProjectTarget.setWorkCompany(sysDeptMapper.selectDeptById(Long.valueOf(infoBaseProject1.getWorkCompany())).getDeptName());
        //主管单位
        infoProjectTarget.setDepartmentId(infoBaseProject1.getDepartmentId());
        infoProjectTarget.setDepartmentName(sysDeptMapper.selectDeptById(infoBaseProject1.getDepartmentId()).getDeptName());
        infoProjectTarget.setCreateByTime(infoBaseProject1.getCreateByTime());
        infoProjectTarget.setEndTime(infoBaseProject1.getEndTime());
        infoProjectTarget.setCreateTime(DateUtils.getNowDate());
        infoProjectTarget.setProjectAttribute(infoBaseProject1.getProjectAttribute());
        return infoProjectTarget;
    }
}
